package blue.http.ext.internal.core.controller;

import blue.http.core.annotation.ContentType;
import blue.http.core.annotation.Http;
import blue.http.core.annotation.HttpMethod;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.exporter.common.TextFormat;
import io.prometheus.client.hotspot.DefaultExports;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-09
 */
@Http(url = "/management/monitor", method = HttpMethod.GET, contentType = ContentType.HTML)
public class MonitorController {
	private static Logger logger = LoggerFactory.getLogger(MonitorController.class);

	private CollectorRegistry registry;

	public MonitorController() {
		DefaultExports.initialize();
		this.registry = CollectorRegistry.defaultRegistry;
	}

	public String index() {
		String text = null;
		try (ByteArrayOutputStream os = new ByteArrayOutputStream();
		     PrintWriter pw = new PrintWriter(os)) {
			TextFormat.write004(pw, this.registry.metricFamilySamples());
			pw.flush();
			text = os.toString(StandardCharsets.UTF_8);
		} catch (IOException e) {
			logger.error("Error,", e);
		}
		return text;
	}

}
